package com.application.screen;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;

import com.example.sispakmobile.R;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

public class KamusScreen extends Activity {
	public String data;
	public List<String> suggest;
	public AutoCompleteTextView autoComplete;
	public ArrayAdapter<String> aAdapter;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.auto_complete);
		suggest = new ArrayList<String>();
		autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
		autoComplete.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable editable) {
				// TODO Auto-generated method stub

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				String newText 						= s.toString();
				new getJson().execute(newText);
			}

		});

	}

	class getJson extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... key) {
			String newText 							= key[0];
			newText 								= newText.trim();
			newText 								= newText.replace(" ", "+");
			try {
				HttpClient hClient 					= new DefaultHttpClient();
				HttpGet hGet 						= new HttpGet(
													"http://10.0.2.2/Sispak/Autocomplete.php?search=kom&limit=5");
				ResponseHandler<String> rHandler 	= new BasicResponseHandler();
				data 								= hClient.execute(hGet, rHandler);
				suggest 							= new ArrayList<String>();
				JSONArray jArray 					= new JSONArray(data);

				for (int i = 0; i < jArray.length(); i++) {
					String SuggestKey = jArray.getString(i); 
					suggest.add(SuggestKey);
				}

			} catch (Exception e) {
				Log.w("Error", e.getMessage());
			}
			runOnUiThread(new Runnable() {
				public void run() {
					aAdapter = new ArrayAdapter<String>(
							getApplicationContext(), R.layout.auto_complete_item, suggest);
					autoComplete.setAdapter(aAdapter);
					aAdapter.notifyDataSetChanged();
				}
			});

			return null;
		}

	}
}